package com.blue.http.config;

import com.blue.core.util.FileUtil;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

/**
 * SSL配置
 *
 * @author zhengjin
 * @since 1.0 2018年03月18日
 */
public class SSLConfig implements InitializingBean
{
	private static Logger logger = LoggerFactory.getLogger(SSLConfig.class);

	private SslContext sslContext;
	private boolean ssl = false;
	private String jks;
	private String pwd;
	private String alias;

	public SSLConfig()
	{
	}

	public SslContext getSslContext()
	{
		return sslContext;
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		if (!ssl)
			return;

		try
		{
			if (jks == null || jks.isEmpty())
			{
				SelfSignedCertificate ssc = new SelfSignedCertificate();
				sslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
				logger.info("使用 Netty 自行颁发的证书");
			}
			else
			{
				char[] passwd = pwd == null ? null : pwd.toCharArray();
				KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
				try (InputStream is = FileUtil.toInputStream(jks))
				{
					ks.load(is, passwd);
				}
				PrivateKey privateKey = (PrivateKey)ks.getKey(alias, passwd);
				X509Certificate x509 = (X509Certificate)ks.getCertificate(alias);
				sslContext = SslContextBuilder.forServer(privateKey, x509).build();
				logger.info("使用证书：{}", jks);
			}
		}
		catch (Exception e)
		{
			logger.error("创建证书失败：", e);
		}
	}

	public void setSsl(boolean ssl)
	{
		this.ssl = ssl;
	}

	public void setPwd(String pwd)
	{
		this.pwd = pwd;
	}

	public void setJks(String jks)
	{
		this.jks = jks;
	}

	public void setAlias(String alias)
	{
		this.alias = alias;
	}

	public boolean isSsl()
	{
		return ssl;
	}

	public String getJks()
	{
		return jks;
	}

	public String getPwd()
	{
		return pwd;
	}

	public String getAlias()
	{
		return alias;
	}
}
